package com.jt.tenant.activity;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetAddFence;
import com.jt.tenant.conn.GetCarGps;
import com.jt.tenant.conn.GetQueryFence;
import com.jt.tenant.conn.GetUpdateFence;
import com.jt.tenant.fragment.HomeFragment;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.text.DecimalFormat;

/**
 * Created by Administrator on 2016/2/15.
 */
public class NotifyFenceActivity extends JTActivity implements View.OnClickListener {

    private DecimalFormat decimalFormat = new DecimalFormat("##.##");

    private LatLng temporarylatLng = new LatLng(45.821143, 126.661377), currentlatLng;

    private int distance = 1000;

    private GeocodeSearch geocoderSearch;

    private MapView mapView;

    private AMap aMap;

    private String lat;

    private String lon;

    private boolean isExit = false;

    private boolean isBack = false;

    public static RefreshDataLinstener refreshLinstener;


    private AsyCallBack asyCallBack = new AsyCallBack() {

        @Override
        public void onSuccess(String toast, int type, Object o) throws Exception {

            if (toast.equals("000")) {

                UtilToast.show(context, "设置成功");

                finish();

            } else {

                UtilToast.show(context, "设置失败");

            }

        }

    };

    private GetAddFence getAddFence = new GetAddFence(asyCallBack);

    private GetUpdateFence getUpdateFence = new GetUpdateFence(asyCallBack);

    private GetQueryFence.Fence currentFence;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_notifyfence);

        mapView = (MapView) findViewById(R.id.fence_map_view);

        mapView.onCreate(savedInstanceState);

        aMap = mapView.getMap();

        geocoderSearch = new GeocodeSearch(this);

        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

            private RegeocodeAddress regeocodeAddress;

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

                if ((currentlatLng = temporarylatLng) != null && regeocodeResult != null && (regeocodeAddress = regeocodeResult.getRegeocodeAddress()) != null) {

                    getUpdateFence.name = getAddFence.name = regeocodeAddress.getDistrict() + " " + regeocodeAddress.getTownship();

                    getUpdateFence.lat = getAddFence.lat = currentlatLng.latitude + "";

                    getUpdateFence.lng = getAddFence.lng = currentlatLng.longitude + "";

                    getUpdateFence.address_type = getAddFence.address_type = "3";

                    setMarkerCircle(currentlatLng, getUpdateFence.address = getAddFence.address = regeocodeAddress.getFormatAddress(), distance);

                }

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }

        });

        currentFence = (GetQueryFence.Fence) getIntent().getSerializableExtra("Fence");

        lat = getIntent().getStringExtra("lat");

        lon = getIntent().getStringExtra("lng");

        isBack = getIntent().getBooleanExtra("isback", true);

        if (currentFence == null) {

            ((TextView) findViewById(R.id.tv_title_name)).setText("电子围栏警报");

            new GetCarGps(new AsyCallBack<GetCarGps.Info>() {

                @Override
                public void onSuccess(String toast, int type, GetCarGps.Info info) throws Exception {

                    setLocation(temporarylatLng = new LatLng(info.lat, info.lng));

                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(temporarylatLng, 13));

                }

            }).execute(this);

        } else {

            getUpdateFence.id = currentFence.id;

            getUpdateFence.name = currentFence.name;

            getUpdateFence.address = currentFence.address;

            getUpdateFence.lat = currentFence.lat + "";

            getUpdateFence.lng = currentFence.lng + "";

            getUpdateFence.address_type = currentFence.addressType;

            getUpdateFence.range_num = currentFence.rangeNum + "";

            ((TextView) findViewById(R.id.tv_title_name)).setText("电子围栏通知");

            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentlatLng = new LatLng(currentFence.lat, currentFence.lng), 13));

            setMarkerCircle(currentlatLng, getUpdateFence.address = currentFence.address, distance = (int) (currentFence.rangeNum * 1000));

            aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lon))).title("").icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),
                            R.mipmap.amap_redcar_position))));

            refreshLinstener = new RefreshDataLinstener() {
                @Override
                public void refresh(GetQueryFence.Fence currentFence, String lat, String lon, boolean isBack) {
                    getUpdateFence.id = currentFence.id;

                    getUpdateFence.name = currentFence.name;

                    getUpdateFence.address = currentFence.address;

                    getUpdateFence.lat = currentFence.lat + "";

                    getUpdateFence.lng = currentFence.lng + "";

                    getUpdateFence.address_type = currentFence.addressType;

                    getUpdateFence.range_num = currentFence.rangeNum + "";

                    ((TextView) findViewById(R.id.tv_title_name)).setText("电子围栏通知");

                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentlatLng = new LatLng(currentFence.lat, currentFence.lng), 13));

                    setMarkerCircle(currentlatLng, getUpdateFence.address = currentFence.address, distance = (int) (currentFence.rangeNum * 1000));

                    aMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lon))).title("").icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(),
                                    R.mipmap.amap_redcar_position))));
                }
            };
        }

    }

    private void setLocation(LatLng latLng) {

        geocoderSearch.getFromLocationAsyn(new RegeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude), 200, GeocodeSearch.AMAP));

    }

    private void setMarkerCircle(LatLng latLng, String address, int distance) {

        aMap.clear();

        aMap.addMarker(new MarkerOptions().position(latLng).snippet(address).draggable(true));

        aMap.addCircle(new CircleOptions().center(latLng).radius(distance).strokeColor(Color.parseColor("#501873f8")).fillColor(Color.parseColor("#501592ff")).strokeWidth(2));

    }

    private void setCarInfo(GetCarGps.Info info) {
        if (info != null) {
            setMarkerCircle(currentlatLng, getUpdateFence.address = currentFence.address, distance = (int) (currentFence.rangeNum * 1000));

            aMap.addMarker(new MarkerOptions().position(new LatLng(info.lat, info.lng)).title("").icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),
                            R.mipmap.amap_redcar_position))));

            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(info.lat, info.lng), 13));
        }
    }

    public void onClick(View view) {

        switch (view.getId()) {



        }

    }

    @Override
    protected void onResume() {

        super.onResume();

        mapView.onResume();

    }

    @Override
    protected void onPause() {

        super.onPause();

        mapView.onPause();

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        mapView.onDestroy();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (HomeFragment.onDismiss == null || !HomeFragment.onDismiss.onDismiss()) {

            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (isBack) {
                    if (isExit == false) {

                        isExit = true;

                        Toast.makeText(NotifyFenceActivity.this, "再按一次退出!", Toast.LENGTH_SHORT).show();

                        Handler mHandler = new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                isExit = false;

                            }
                        };
                        mHandler.sendEmptyMessageDelayed(0, 3000);

                        return true;

                    } else {

                        JTApplication.INSTANCE.AppExit(context);

                        return false;

                    }
                } else {
                       finish();
                }


            }

        }

        return true;
    }

    @Override
    public void onBack(View v) {

        if (isBack) {
            if (isExit == false) {

                isExit = true;

                Toast.makeText(NotifyFenceActivity.this, "再按一次退出!", Toast.LENGTH_SHORT).show();

                Handler mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        isExit = false;

                    }
                };
                mHandler.sendEmptyMessageDelayed(0, 3000);


            } else {

                JTApplication.INSTANCE.AppExit(context);

            }
        } else {
            finish();
        }
    }

    public abstract class RefreshDataLinstener{

        public abstract void refresh(GetQueryFence.Fence currentFence,String lat,String lon,boolean isBack);

    }
}